var qs = require("querystring"),
  formidable = require("formidable"),
  util = require("util"),
  fs = require("fs-extra"),
  im = require("imagemagick"),
  url = require('url'),
  util = require('util');
var path = require('path');
var basedir = path.resolve(__dirname, "..");
var source = path.resolve(__dirname);

function process(req, res) {
  var urlQuery = url.parse(req.url, true).query;
  console.log(urlQuery)
  if (urlQuery.option == "show") {
    console.log("show")
    show(req, res, urlQuery.name, urlQuery.size)
  } else {
    upload(req, res);
    // res.writeHead(200,{'Content-Type': 'text/plain','Content-Length':'upload'.length});
    // res.end('upload');
  }
}



function upload(req, res) {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    res.writeHead(200, {
      'Content-Type': 'text/plain'
    });
    res.write("recieved upload: \n\n");
    res.end(util.inspect({
      fields: fields,
      files: files
    }));
  });

  form.on('end', function(fields, files) {
    console.log(this.openedFiles.length)
    if (this.openedFiles.length > 0) {
      var temp_path = this.openedFiles[0].path;
      var file_name = this.openedFiles[0].name;
      var new_location = 'src/uploads/';

      fs.copy(temp_path, new_location + file_name+".png", function(err) {
        if (err) {
          console.error(err);
        } else {
          console.log("success");
          res.writeHead(202, {
            'Content-Type': 'text/plain',
            'Content-Length': 'success'.length
          });
          res.end('success');
        }
      });
    } else {}
  });
}

function show(req, res, img, size) {
  console.log("show: " + img + " with size: " + size)
  im.resize({
    srcPath: basedir + '/uploads/' + img + '.png',
    width: parseInt(size)
  }, function(err, stdout, stderr) {
    if (err) throw err;
    res.writeHead(200, {
      "Content-Type": "image/png"
    });
    res.write(stdout, "binary");
    res.end();
  });
}

exports.process = process;